/// ****************************************************************************
/// Author:	        Robin Zhu
/// Create Date:	2011-11-1
/// Purpose: 		数据访问上下文工厂类文件
/// ****************************************************************************
/// Modify By		Date			Remark
/// ****************************************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

using RB.DataAccess.Configuration;


namespace RB.DataAccess
{
    /// <summary>
    /// 数据访问上下文工厂类
    /// </summary>
    internal static class DataContextFactory
    {
        internal static DataContext Create()
        {
            var config = DataConfigManager.Load();
            var contextConfig = config.Contexts[config.DefaultContext];

            return Create(contextConfig);
        }

        internal static DataContext Create(string configName)
        {
            var config = DataConfigManager.Load();
            var contextConfig = config.Contexts[configName];

            return Create(contextConfig);
        }

        private static DataContext Create(DataContextConfigElement contextConfig)
        {
            DataContext result = null;
            if (contextConfig != null)
            {
                string typeName = contextConfig.Type;
                string connectionStringName = contextConfig.ConnectionStringName;
                var connectionSettings = ConfigurationManager.ConnectionStrings[connectionStringName];
                Type t = Type.GetType(typeName);
                result = (DataContext)Activator.CreateInstance(t);
                result.Initialize(connectionSettings.ConnectionString, contextConfig.Parameters);
            }

            return result;
        }
    }
}
